/*
 * Scene.cpp
 *
 *  Created on: Oct 26, 2012
 *      Author: Bhupendra Aole
 */

#include <iostream>
#include <string>
#include "Scene.h"
#include "util.h"
#include "DXObjectFactory.h"

using namespace std;

Scene::Scene( string n ) :
		name( n ) {
}

void Scene::createNode( TiXmlNode* node, aole::DXEngine* engine ) {
	aole::DXObject* obj = aole::DXObjectFactory::create( node->Value() );
	if ( !obj ) {
		cout << "No type found: '" << node->Value() << "'\n";
		return;
	}

	// get attributes
	TiXmlElement* e = node->ToElement();
	for ( TiXmlAttribute *a = e->FirstAttribute(); a != NULL; a = a->Next() ) {
		obj->setProperty( a->Name(), a->Value() );
	}
	// get child nodes
	for ( TiXmlNode* c = node->FirstChild(); c != 0; c = c->NextSibling() ) {
		//if ( !strcmp( c->Value(), "color" ) ) {
			e = c->ToElement();
			for ( TiXmlAttribute *a = e->FirstAttribute(); a != NULL;
					a = a->Next() ) {
				obj->setProperty( a->Name(), a->Value() );
			}
		//}
	}

	obj->create( engine );

	objects.push_back( obj );
}

void Scene::render( aole::DXEngine* engine ) {
	vector<aole::DXObject*>::iterator it;
	for ( it = objects.begin(); it < objects.end(); it++ ) {
		((aole::DXObject*) *it)->render( engine );
	}
}

void Scene::load( aole::DXEngine* engine ) {
	string file = name + ".xml";
	TiXmlDocument doc( file );
	bool loadOkay = doc.LoadFile();

	if ( !loadOkay ) {
		cout << "Error in loading Game Flow file: " << file;
		return;
	}

	TiXmlNode* eVisq = doc.FirstChild();
	// get visq element
	if ( !UTIL::isNode( "visq", eVisq ) ) {
		cout << "Error in getting 'visq' element in file: " << file;
		return;
	}
	// TODO: check for visq version

	// get scenes element
	for ( TiXmlNode* node = eVisq->FirstChild(); node != NULL;
			node = node->NextSibling() ) {
		createNode( node, engine );
	}
}
